#app/api/user_api.rb
class UserAPI < Grape::API
  # 返回的数据为json
  format :json
  before do
    header 'Access-Control-Allow-Origin',  '*' 
    header 'Content-Type', 'text/plain;charset=utf-8'
    header 'Access-Control-Allow-Methods','*'
    header 'Access-Control-Expose-Headers',''
    header 'Access-Control-Allow-Headers','Authorization,content-type,accept,Access-Control-Allow-Origin'
  end  

  prefix :api

  # mount SessionsController
  # mount UsersController

  # 根据名称获取用户信息
  get '/user/get_user' do
    # binding.pry
    user = User.where(username: params[:username])
    {user: user}

  end
  post 'post_user' do
    user = User.where(username: params[:username])
    {user: user}
  end

  get 'test' do
      users = User.all
    {message: users}
  end
  
  get 'find_by_test' do
    user = User.find_by(username: params[:username], password: params[:password])
    {message: user}
  end
      
  def destroy
    session[:user_id] = nil
    flash[:notice] = "退出成功"
    redirect_to root_path
  end
  
  # 参数校验
  params do
    requires :username, type: String, desc: '用户名'
    requires :password, type: String, desc: '密码'
  end

  post '/user/add_user' do
    @user = User.new(username: params[:username], password: params[:password])
    if @user.save
      {status:200}
    else
      {status:500}
    end
  end

  post '/user/login' do
    @user = User.find_by(username: params[:username], password: params[:password])
    if @user
      {status:200,code:0,token:1,user:@user.username}
    else
      {status:500}
    end 
  end

end
  